package com.buka.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.buka.domain.ResponseResult;
import com.buka.enums.AppHttpCodeEnum;
import com.buka.pojo.Category;
import com.buka.service.CategoryService;
import com.buka.util.BeanCopyUtils;
import com.buka.util.WebUtils;
import com.buka.vo.CategoryVo;
import com.buka.vo.ExcelCategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/content/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/listAllCategory")
    public ResponseResult listAllCategory() {
        List<CategoryVo> list = categoryService.listAllCategory();
        return ResponseResult.okResult(list);
    }

    @PreAuthorize("@ps.hasPermission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx", response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryService.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);
        } catch (Exception e) {
            //如果出现异常也要响应json
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR)));
        }
    }

    @GetMapping("/list")
    public ResponseResult list(int pageNum, int pageSize, String name, String status) {
        return categoryService.list(pageNum, pageSize, name, status);
    }

    @PostMapping
    public ResponseResult addCategory(@RequestBody Category category) {
        return categoryService.addCAtegory(category);
    }

    @GetMapping("/{id}")
    public ResponseResult getCategoryById(@PathVariable("id") int id) {
        return categoryService.getCategoryById(id);
    }

    @PutMapping
    public ResponseResult updateCategoryById(@RequestBody Category category) {
        return categoryService.updateCategoryById(category);
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteCategoryById(@PathVariable("id") int id) {
        return categoryService.deleteCategoryById(id);
    }
}
